package pers.smalltown.ourspace.record;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.ws.rs.Path;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/v1/ourrecord")
public class RecordController {
	@Autowired
	private OurRecordDao ourRecordDao;
	@Autowired
	private RecordDeal recordDeal;
	@Autowired
	private RecordPreDeal recordPreDeal;

	@GetMapping("/{id}")
	public Record getRecordById(@PathVariable int id) {
		return ourRecordDao.selectRecord(id);
	}
	
	@RequestMapping("/deal/{platform}")
	@Transactional(rollbackFor = {RuntimeException.class, Error.class})
	public String dealRecord(@PathVariable String platform) {
		try {
			recordDeal.deal(platform);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("err");
		}
		return "deal record";
	}
	
	@RequestMapping("/preDeal/{platform}")
	@Transactional(rollbackFor = {RuntimeException.class, Error.class})
	public String preDealRecord(@PathVariable String platform) {
		try {
			recordPreDeal.deal(platform);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("err");
		}
		return "pre deal record";
	}
	
	@RequestMapping("/oneday/{year}/{month}/{day}")
	public List<Record> getOneDayRecord(@PathVariable String year, @PathVariable String month, @PathVariable String day) {
		List<Record> resultList = ourRecordDao.selectOneDayByDate(new QueryDate(year, month, day));
		return resultList;
	}

	// TODO 应支持分页
	@RequestMapping("/search/{keyword}")
	public List<Record> searchKeyword(@PathVariable String keyword) {
		List<Record> resultList = ourRecordDao.selectByContent(keyword);
		return resultList;
	}

	@RequestMapping("/statistic/{keyword}")
	public List<RecordStatistic> statisticsKeyword(@PathVariable String keyword) {
		List<RecordStatistic> resultList = ourRecordDao.statisticByContent(keyword);
		RecordStatistic total = new RecordStatistic();
		total.setDescription("Total");
		int totalNum = 0;
		for (RecordStatistic one : resultList) {
			totalNum += one.getCount();
		}
		total.setCount(totalNum);
		resultList.add(total);
		return resultList;
	}
}
